package com.alibaba.algo.components.yapi;

import java.lang.reflect.Method;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.algo.components.yapi.annotations.Api;
import com.alibaba.algo.components.yapi.service.YapiOpenService;
import com.alibaba.algo.components.yapi.service.YapiService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 接口自动注册yapi工具类
 * @author: malin
 * @date: 2021年2月22日 下午2:47:45
 */
@Slf4j
@Component
public class YapiAutoRegisterService {
	@Autowired
	private YapiService yapiService;
	@Autowired
	private YapiOpenService yapiOpenService;

	/**
	 * @Description: 接口自动注册yapi
	 * @param: controllerClass 接口类
	 * @param: interfaces      接口名称
	 * @author: malin
	 * @date: 2021年2月22日 下午2:53:41
	 */
	public void yapiAutoRegister(Class<?> controllerClass, final String... interfaces) {
		yapiOpenService.initData();
		Api apiAnnotatio = controllerClass.getAnnotation(Api.class);
		if (apiAnnotatio == null) {
			return;
		}
		String catName = apiAnnotatio.catName();
		log.info("beanName:{},apiAnnotatio catname:{}", controllerClass.getName(), catName);
		if (StringUtils.isEmpty(catName)) {
			return;
		}
		Integer catId = yapiService.getCatId(apiAnnotatio);
		if (catId == null) {
			return;
		}
		Method[] methods = new Method[interfaces.length];
		if (!ArrayUtils.isEmpty(interfaces)) {
			int i = 0;
			for (final String interfaceName : interfaces) {
				Method m = ReflectionUtils.findMethod(controllerClass, interfaceName, null);
				if (m != null) {
					methods[i] = m;
					++i;
				}
			}
		} else {
			methods = ReflectionUtils.getAllDeclaredMethods(controllerClass);
		}
		if (methods == null || methods.length == 0) {
			return;
		}
		yapiService.registerYapi(catId, controllerClass, methods);
	}
}
